<?php

class Request
{
    /**
     * 发起HTTP请求
     *
     * @param string $url 请求URL
     * @param array $data 请求数据
     * @param string $method 请求方法 GET|POST
     * @param string $contentType 请求内容类型
     * @param array $headers 附加的请求头
     * @param array $options cURL额外选项
     * @return array 返回结果数组，包含响应内容和状态码
     * @throws Exception
     */
    public static function request(
        string $url,
        array $data = [],
        string $method = 'GET',
        string $contentType = 'form',
        array $headers = [],
        array $options = []
    ): array {
        if (!in_array(strtoupper($method), ['GET', 'POST'])) {
            throw new Exception('Unsupported HTTP method');
        }

        $ch = curl_init();

        // 设置请求方法
        if (strtoupper($method) === 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
        } else {
            if (!empty($data)) {
                $url = $url . (strpos($url, '?') === false ? '?' : '&') . http_build_query($data);
            }
        }

        // 根据内容类型设置请求数据和请求头
        switch (strtolower($contentType)) {
            case 'json':
                $postData = json_encode($data);
                $headers = array_merge($headers, [
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($postData)
                ]);
                break;

            case 'form':
                $postData = http_build_query($data);
                $headers = array_merge($headers, [
                    'Content-Type: application/x-www-form-urlencoded'
                ]);
                break;

            case 'multipart':
                // 对于multipart/form-data，让cURL自动处理
                $postData = $data;
                // 不要设置Content-Type头，cURL会自动设置正确的boundary
                break;

            case 'xml':
                $postData = self::arrayToXml($data);
                $headers = array_merge($headers, [
                    'Content-Type: application/xml',
                    'Content-Length: ' . strlen($postData)
                ]);
                break;

            case 'text':
                $postData = is_array($data) ? implode("\n", $data) : (string)$data;
                $headers = array_merge($headers, [
                    'Content-Type: text/plain',
                    'Content-Length: ' . strlen($postData)
                ]);
                break;

            default:
                throw new Exception('Unsupported content type');
        }

        // 如果是POST请求，设置POST数据
        if (strtoupper($method) === 'POST') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        }

        // 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // 设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);

        // 设置SSL验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        // 应用额外选项
        foreach ($options as $option => $value) {
            curl_setopt($ch, $option, $value);
        }

        // 执行请求
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new Exception('CURL error: ' . $error);
        }

        curl_close($ch);

        return [
            'status' => $httpCode,
            'body' => $response
        ];
    }

    /**
     * 发起GET请求
     *
     * @param string $url 请求URL
     * @param array $data 请求数据
     * @param string $contentType 内容类型
     * @param array $headers 附加请求头
     * @param array $options cURL额外选项
     * @return array
     * @throws Exception
     */
    public static function get(
        string $url,
        array $data = [],
        string $contentType = 'form',
        array $headers = [],
        array $options = []
    ): array {
        return self::request($url, $data, 'GET', $contentType, $headers, $options);
    }

    /**
     * 发起POST请求
     *
     * @param string $url 请求URL
     * @param array $data 请求数据
     * @param string $contentType 内容类型
     * @param array $headers 附加请求头
     * @param array $options cURL额外选项
     * @return array
     * @throws Exception
     */
    public static function post(
        string $url,
        array $data = [],
        string $contentType = 'form',
        array $headers = [],
        array $options = []
    ): array {
        return self::request($url, $data, 'POST', $contentType, $headers, $options);
    }

    /**
     * 将数组转换为XML
     *
     * @param array $data
     * @param string $rootNode
     * @return string
     */
    private static function arrayToXml(array $data, string $rootNode = 'root'): string
    {
        $xml = new SimpleXMLElement('<' . $rootNode . '/>');
        self::addArrayToXml($xml, $data);
        return $xml->asXML();
    }

    /**
     * 递归添加数组到XML
     *
     * @param SimpleXMLElement $xml
     * @param array $data
     */
    private static function addArrayToXml(SimpleXMLElement $xml, array $data)
    {
        foreach ($data as $key => $value) {
            if (is_array($value)) {
                if (is_numeric($key)) {
                    $key = 'item';
                }
                $subnode = $xml->addChild($key);
                self::addArrayToXml($subnode, $value);
            } else {
                if (is_numeric($key)) {
                    $key = 'item';
                }
                $xml->addChild($key, htmlspecialchars($value));
            }
        }
    }
}
